// ImageSerializer.java
package fun.sssdnsy.media.image;

import javafx.beans.binding.DoubleBinding;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 图片序列化工具
 */
public class ImageSerializer {

    // 自定义文件扩展名
    private static final String IMAGE_EXTENSION = ".dat";

    /**
     * 将JavaFX Image序列化为加密友好的字节数组
     */
    public static byte[] serializeImage(Image image, DoubleBinding width,DoubleBinding height) throws IOException {
        BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
        ResizableImageView imageView = new ResizableImageView(image, width,height);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "PNG", baos); // 先保存为PNG格式的字节流
        return baos.toByteArray();
    }

    /**
     * 将字节数组保存为自定义格式文件
     */
    public static String saveToSecureFile(byte[] data, String outputDir) throws IOException {
        // 创建唯一文件名
        String filename = UUID.randomUUID().toString() + IMAGE_EXTENSION;
        Path path = Paths.get(outputDir, filename);

        // TODO 简单混淆：反转字节（后续可替换为加密算法）
        byte[] obfuscated = new byte[data.length];
        for (int i = 0; i < data.length; i++) {
            obfuscated[i] = (byte) (~data[i]); // 按位取反
        }

        Files.write(path, obfuscated);
        return filename;
    }

    /**
     * 获取或创建图片存储目录
     */
    public static String getImageStoragePath() {
        String userHome = System.getProperty("user.dir");
        Path storageDir = Paths.get(userHome, "secure_images");
        if (!Files.exists(storageDir)) {
            try {
                Files.createDirectories(storageDir);
            } catch (IOException e) {
                throw new RuntimeException("无法创建图片存储目录", e);
            }
        }
        return storageDir.toString();
    }
}
